package com.molichuxing.gateway.bff.terminal.services.impl;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.TabDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.gateway.bff.terminal.convertor.Convert;
import com.molichuxing.gateway.bff.terminal.entity.request.modify.DeviceModifyVo;
import com.molichuxing.gateway.bff.terminal.entity.response.DeviceAppVo;
import com.molichuxing.gateway.bff.terminal.entity.response.DeviceErrorListVo;
import com.molichuxing.gateway.bff.terminal.entity.response.DeviceErrorVo;
import com.molichuxing.gateway.bff.terminal.entity.response.DeviceListVo;
import com.molichuxing.gateway.bff.terminal.services.TerminalBffService;
import com.molichuxing.gateway.property.TerminalOnlineStatusEnum;
import com.molichuxing.gateway.utils.RequestAttrUtil;
import com.molichuxing.services.business.dto.request.modify.StoreDeviceBizModifyDto;
import com.molichuxing.services.business.dto.response.DeviceInfoBizDto;
import com.molichuxing.services.business.service.DeviceBizService;
import com.molichuxing.services.infrastructure.dto.response.DeviceDetailDto;
import com.molichuxing.services.infrastructure.dto.response.DeviceDto;
import com.molichuxing.services.infrastructure.dto.response.DeviceMonitorDto;
import com.molichuxing.services.infrastructure.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 经销商信息相关bff
 *
 * @author zhaopenghui
 * @date 2019年8月26日
 */
@Service("terminalBffService")
public class TerminalBffServiceImpl implements TerminalBffService {
    private static final Logger logger = LoggerFactory.getLogger(TerminalBffServiceImpl.class);

    @Resource
    private DeviceBizService deviceBizService;
    @Resource
    private DeviceService deviceService;
    @Resource
    DeviceDetailService deviceDetailService;
    @Resource
    DeviceMonitorService deviceMonitorService;
    @Resource
    private StoreService storeService;
    @Resource
    private StoreDeviceService storeDeviceService;

    /**
     * 终端分页列表
     *
     * @param params
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public Paged<DeviceListVo> getDevicePage(Map<String, Object> params, Integer pageNum, Integer pageSize) throws Exception {
        Integer dealerId = RequestAttrUtil.getCurrentDealerId();
        params.put("dealerId", dealerId);
        Integer onlineStatus = ObjectCastUtil.castInteger(params.get("onlineStatus"));
        LocalDateTime startLastConnectTime = ObjectCastUtil.getDayStart(params.get("startLastConnectTime"));
        LocalDateTime endLastConnectTime = ObjectCastUtil.getDayEnd(params.get("endLastConnectTime"));
        LocalDateTime nowTime = LocalDateTime.now();
        if (onlineStatus != null && TerminalOnlineStatusEnum.ONLINE.getValue() == onlineStatus) {
            params.put("startHeartTime", nowTime.minusMinutes(1));
            params.put("endHeartTime", nowTime);
        } else if (onlineStatus != null && TerminalOnlineStatusEnum.OFFLINE.getValue() == onlineStatus) {
            LocalDateTime endTime = nowTime.minusMinutes(1);
            if (startLastConnectTime != null && endLastConnectTime != null) {
                if (endLastConnectTime.isBefore(endTime)) {
                    endTime = endLastConnectTime;
                }
                params.put("startHeartTime", startLastConnectTime);
            }
            params.put("endHeartTime", endTime);
        } else {
            if (startLastConnectTime != null && endLastConnectTime != null) {
                params.put("startHeartTime", startLastConnectTime);
                params.put("endHeartTime", endLastConnectTime);
            }
        }

        Paged<DeviceInfoBizDto> devicePage = deviceBizService.getDevicePage(params, pageNum, pageSize);
        List<DeviceInfoBizDto> deviceInfoBizDtoList = devicePage.getList();
        if (null == deviceInfoBizDtoList) {
            Paged<DeviceListVo> paged = new Paged<DeviceListVo>();
            return getPageTab(paged, nowTime, dealerId);
        }

        List<String> cpuList = new ArrayList<>();
        for (DeviceInfoBizDto deviceInfoBizDto : deviceInfoBizDtoList) {
            String cpu = deviceInfoBizDto.getCpu();
            cpuList.add(cpu);
        }
        List<DeviceDetailDto> deviceDetailList = deviceDetailService.getDeviceDetailList(cpuList);
        List<DeviceListVo> deviceListVo = Convert.toDeviceListVoList(deviceInfoBizDtoList, deviceDetailList);
        Paged<DeviceListVo> paged = new Paged<DeviceListVo>(deviceListVo, devicePage.getTotal(), pageSize);
        return getPageTab(paged, nowTime, dealerId);
    }

    /**
     * 故障
     *
     * @param params
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public Paged<DeviceErrorListVo> getDeviceErrorPage(Map<String, Object> params, Integer pageNum, Integer pageSize) throws Exception {
        Integer status = ObjectCastUtil.castInteger(params.get("status"));
        if (status != null) {
            List<String> cpuList = deviceDetailService.getCpuByStatus(status);
            if (null == cpuList || cpuList.size() < 1) {
                cpuList.add("0");
            }
            params.put("cpuList", cpuList);
        }

        Paged<DeviceInfoBizDto> devicePage = deviceBizService.getDevicePage(params, pageNum, pageSize);
        List<DeviceInfoBizDto> deviceInfoBizDtoList = devicePage.getList();
        if (null == deviceInfoBizDtoList) {
            return new Paged<DeviceErrorListVo>();
        }

        List<String> cpuList = new ArrayList<>();
        for (DeviceInfoBizDto deviceInfoBizDto : deviceInfoBizDtoList) {
            String cpu = deviceInfoBizDto.getCpu();
            cpuList.add(cpu);
        }
        List<DeviceDetailDto> deviceDetailList = deviceDetailService.getDeviceDetailList(cpuList);
        List<DeviceErrorListVo> deviceListVo = Convert.toDeviceErrorListVoList(deviceInfoBizDtoList, deviceDetailList);
        return new Paged<DeviceErrorListVo>(deviceListVo, devicePage.getTotal(), pageSize);
    }


    /**
     * 获取分页tab值
     *
     * @return
     * @throws Exception
     */
    private Paged<DeviceListVo> getPageTab(Paged<DeviceListVo> paged, LocalDateTime nowTime, Integer dealerId) throws Exception {
        List<Integer> deviceIdList = null;
        if (dealerId != null) {
            List<Integer> storeIdList = storeService.getStoreIdByDealer(dealerId);
            deviceIdList = storeDeviceService.getDeviceIdByStoreIds(storeIdList);
            if (deviceIdList == null || deviceIdList.size() < 1) {
                deviceIdList = new ArrayList<>();
                deviceIdList.add(0);
            }
        }
        Integer allCount = deviceService.getCount(deviceIdList,null, null);
        Integer onlineCount = deviceService.getCount(deviceIdList,nowTime.minusMinutes(1), nowTime);
        Integer offlineCount = allCount - onlineCount;
        List<TabDto> tabList = new ArrayList<>();
        for (TerminalOnlineStatusEnum statusEnum : TerminalOnlineStatusEnum.values()) {
            int value = statusEnum.getValue();
            String name = statusEnum.getName();
            Integer count = 0;
            if (TerminalOnlineStatusEnum.ALL.getValue() == value) {
                count = allCount;
            } else if (TerminalOnlineStatusEnum.ONLINE.getValue() == value) {
                count = onlineCount;
            } else if (TerminalOnlineStatusEnum.OFFLINE.getValue() == value) {
                count = offlineCount;
            }

            if (null == count) {
                count = 0;
            }

            TabDto tabDto = new TabDto();
            tabDto.setName(name);
            tabDto.setType(value);
            tabDto.setCount(count);
            tabList.add(tabDto);
        }

        return paged.setTab(tabList);
    }

    /**
     * 编辑设备
     *
     * @param deviceModifyVo
     * @return
     * @throws Exception
     */
    @Override
    public Boolean modifyDevice(DeviceModifyVo deviceModifyVo) throws Exception {
        StoreDeviceBizModifyDto storeDeviceBizModifyDto = Convert.toStoreDeviceBizModifyDto(deviceModifyVo);
        return deviceBizService.modifyStoreDevice(storeDeviceBizModifyDto);
    }

    /**
     * 资源
     *
     * @param deviceId
     * @return
     */
    @Override
    public List<DeviceAppVo> getDeviceAppList(Integer deviceId) {
        DeviceDto deviceDto = deviceService.getDeviceById(deviceId);
        if (null == deviceDto) {
            throw new BizException("设备不存在");
        }

        String cpu = deviceDto.getCpu();
        DeviceDetailDto deviceDetailDto = deviceDetailService.getDeviceDetailByCpu(cpu);
        return Convert.toDeviceAppVoList(deviceDetailDto);
    }

    /**
     * 故障
     *
     * @param deviceId
     * @return
     */
    @Override
    public DeviceErrorVo getDeviceError(Integer deviceId) {
        DeviceInfoBizDto deviceInfoBizDto = deviceBizService.getDeviceStore(deviceId);
        String cpu = deviceInfoBizDto.getCpu();
        List<DeviceMonitorDto> deviceMonitorList = deviceMonitorService.getDeviceMonitorList(cpu);
        return Convert.toDeviceErrorVo(deviceInfoBizDto, deviceMonitorList);
    }

}
